package com.wetool.wechat.controller;

import com.wetool.common.model.Message;
import com.wetool.common.model.Result;
import com.wetool.common.wechat.WechatResult;
import com.wetool.wechat.entity.MinaAccountRelation;
import com.wetool.wechat.feign.MinaFeignClient;
import com.wetool.wechat.model.open.MinaAccessTokenResponse;
import com.wetool.wechat.model.open.MinaReturnThirdSession;
import com.wetool.wechat.service.MinaService;
import com.wetool.wechat.util.ThirdSessionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import redis.clients.jedis.Jedis;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 微信小程序接口
 */
@Api(description = "微信小程序接口")
@RestController()
@RequestMapping(value = "/mina")
@EnableFeignClients
public class MinaController {

	private final static Logger LOGGER = LoggerFactory.getLogger(MinaController.class);

	@Autowired
	private MinaFeignClient minaFeignClient;
	
	@Autowired
	private MinaService minaService;

	public static final String APPID = "wxa641c599fa36c53e";
	public static final String SECRET = "29a06ef261d7c094922c941616748e14";

	private Jedis redis;


	/**
	 * 微信小程序登录接口
	 *APPID：wxa641c599fa36c53e  APPsecret：29a06ef261d7c094922c941616748e14
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "微信小程序登录", notes = "微信小程序登录")
	@ApiResponses(value = { @ApiResponse(code = 0, message = "操作成功"), @ApiResponse(code = 1, message = "操作成功"),
			 @ApiResponse(code = 161110, message = "微信小程序登录认证失败", response =
			 WechatResult.class),
			 @ApiResponse(code = 161111, message = "微信小程序登录凭证code为无效", response =
			 WechatResult.class),
			 @ApiResponse(code = 161112, message = "无法获取WebAccessToken", response =
			 WechatResult.class),
			 @ApiResponse(code = 161113, message = "第三方3rdSession过期", response =
			 WechatResult.class)
	})
	@GetMapping(value = "/onLogin")
	public ResponseEntity<Message<?>> onLogin(String code) {
		LOGGER.info("进入接口：微信小程序登录  >  code:{}", code);
		// 通过code换取网页授权session_key
			String JSCODE = code;
			if( StringUtils.isEmpty(code)) {//传入的code为空或空串
				Message<?> message = new Message<>(WechatResult.MINA_CODE_ERROR,"传入的code值为空");
				LOGGER.info("退出接口：微信小程序登录失败 < 返回参数【{}】", message);
				return ResponseEntity.ok(message);}
			//从微信服务器获得session_key,openid,unionid
			MinaAccessTokenResponse resp = minaFeignClient.jscode2session(APPID, SECRET, JSCODE);
			String sessionkey = resp.getSessionKey();
			String minaOpenid = resp.getOpenId();
//			String unionId = resp.getUnionId(); //获取不到unionId，不具备微信开放平台帐号必须已完成开发者资质认证
			//判断session_key和openid是否获取到
			//如果获取不到
			if(StringUtils.isEmpty(sessionkey)|| StringUtils.isEmpty(minaOpenid)) {
				Message<?> message = new Message<>(WechatResult.MINA_NOT_FOUND_WEBACCESSTOKEN,"WebAccessToken为空,请求失败");
				return ResponseEntity.ok(message);}
			//获取到session_key和openid
			//拼接minaOpenid和session_key 字符串，json格式
			StringBuffer sb = new StringBuffer();
			String value = sb.append("{minaOpenid:"+minaOpenid).append(",session_key:"+sessionkey+"}").toString();
				//通过工具类生成16位3rdSession会话密钥，也可以进行加密  
				String thirdSession = new ThirdSessionUtil().getThirdSessionByUUId();
				redis = new Jedis("192.168.1.10", 6379); 
				redis.set(thirdSession, value);
				//设置thirdsession有效时间为一天
				redis.expire(thirdSession, 60*60*24*1);
			
				//验证微信用户身份
				//通过minaOpenid查询小程序用户是否在存在，如果不存在创建新用户，存储信息
				MinaAccountRelation minaAccountRelation = minaService.findByMinaOpenid(minaOpenid);
				//如果查询不到用户，创建小程序新用户保存到数据库
				if(minaAccountRelation == null) {
					MinaAccountRelation entity = new MinaAccountRelation(); 
					//绑定sessionkey和minaopenid和thirdSession，在数据库表中添加小程序新用户
					entity.setSession_key(sessionkey);
					entity.setMinaOpenid(minaOpenid);
					entity.setThirdSession(thirdSession);
//					entity.setUnionId(unionId);
					minaService.save(entity);}
				//登录验证成功，返回thirdsession
				MinaReturnThirdSession return3rdSession = new MinaReturnThirdSession();
				return3rdSession.setThirdSession(thirdSession);
				Message<MinaReturnThirdSession> message = new Message<MinaReturnThirdSession>(Result.SUCCESS,return3rdSession);
				LOGGER.info("退出接口：微信小程序登录 < 返回参数【{}】", message);
				return ResponseEntity.ok(message);
}
	@ApiOperation(value = "微信小程序验证登录", notes = "微信小程序验证登录")
	@ApiResponses(value = { @ApiResponse(code = 0, message = "操作成功"), @ApiResponse(code = 1, message = "操作成功"),
			 @ApiResponse(code = 161110, message = "微信小程序登录认证失败", response =
			 WechatResult.class),
			 @ApiResponse(code = 161111, message = "微信小程序登录凭证code为无效", response =
			 WechatResult.class),
			 @ApiResponse(code = 161112, message = "无法获取WebAccessToken", response =
			 WechatResult.class),
			 @ApiResponse(code = 161113, message = "第三方3rdSession过期", response =
			 WechatResult.class)
			 
	})
	@GetMapping(value = "/signin")
	public ResponseEntity<Message<?>> signIn(String thirdSession){
		LOGGER.info("进入接口：微信小程序登录  >  thirdSession:{}", thirdSession);
		redis = new Jedis("192.168.1.10",6379);
		Long time = null;
		//获得thirdSession剩余时间
		time = redis.ttl(thirdSession);
		//thirdSession失效需要重新登录
		if(time <= 0) {
			//将数据表中thirdSession失效用户的thirdSession值改变为null
			minaService.updateThirdSession(thirdSession);
			Message<?> message = new Message<>(WechatResult.MINA_TIMEOUT_3RDSESSION,"thirdSession失效，重新登录");
			LOGGER.info("退出接口：微信小程序验证登录失败 < 返回参数【{}】", message);
			return ResponseEntity.ok(message);}
		//thirdSession有效，存在redis缓存中
		//刷新thirdSession有效时间
		redis.expire(thirdSession, 60*60*24);
//		String str = redis.get(thirdSession);
//		//解析json格式的str
//		JSONObject json1 = JSONObject.parseObject(str);
//		String minaOpenid = json1.getString("minaOpenid");
//		String session_key = json1.getString("session_key");
		Message<?> message = new Message<>(Result.SUCCESS,"微信小程序登录验证成功");
		LOGGER.info("退出接口：微信小程序验证登录成功 < 返回参数【{}】", message);
		return ResponseEntity.ok(message);
	}
	
}
